package cn.jn.lhm.netty.part08.chat.core;

import cn.jn.lhm.netty.part08.chat.handler.*;
import cn.jn.lhm.netty.part08.chat.protocol.ScopeMessageCodec;
import cn.jn.lhm.netty.part08.chat.protocol.SharableMessageCodec;
import cn.jn.lhm.netty.part08.chat.session.SessionFactory;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/10/31 - 22:23
 **/
@Slf4j
public class ChatServer {
    public static final LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
    private static final SharableMessageCodec MESSAGE_CODEC = new SharableMessageCodec();
    public static void main(String[] args) {
        NioEventLoopGroup boos = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup(2);
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boos, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel client) throws Exception {
                    //client.pipeline().addLast(new ProtocolFrameDecoder());
                    client.pipeline().addLast(new ScopeMessageCodec());
                    client.pipeline().addLast(LOGGING_HANDLER);
                    // 当处于读空闲的时候回触发 {@code IdleState#READER_IDLE} 事件
                    client.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                    client.pipeline().addLast(new ChannelDuplexHandler() {
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            if (evt instanceof IdleStateEvent de) {
                                if (de.state() == IdleState.READER_IDLE) {
                                    log.info("{} 断开连接", SessionFactory.getSession().getUsername(ctx.channel()));
                                    SessionFactory.getSession().unbind(ctx.channel());
                                    ctx.channel().close();
                                }
                            }
                        }
                    });

                    // 处理登录操作,包含校验|欢迎语
                    client.pipeline().addLast(new ServerLoginHandler());

                    // 处理后续的业务逻辑
                    client.pipeline().addLast(new ServerChatHandler());
                    // 群聊创建处理器
                    client.pipeline().addLast(new ServerCreateGroupMessageHandler());
                    // 群聊消息处理器
                    client.pipeline().addLast(new ServerGroupChatHandler());
                    // 退出处理器
                    client.pipeline().addLast(new ServerQuitHandler());
                }
            });
            ChannelFuture future = serverBootstrap.bind(8080).sync();
            future.channel().closeFuture().sync();
        } catch (Exception e) {
            log.error("server error...", e);
        } finally {
            boos.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
